package main;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import DBClasses.User;

public class Login extends BaseServlet
{
	@SuppressWarnings("unchecked")
	@Override
	protected void action(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException
	{
		HttpSession session = req.getSession();
		UserView user = (UserView)session.getAttribute("user");
		String result="fail";
		if (user == null)
		{
			PersistenceManager manager = PMF.get().getPersistenceManager();
			String login = req.getParameter("login").toString();
			String pass = req.getParameter("pswrd").toString();
			List<User> users = (List<User>) manager.newQuery(
					"select from " + User.class.getName() + " where login == '"
							+ login + "'").execute();			
			if (users.size() > 0 && users.get(0).getPassword().equals(pass))
			{				
				UserView view = new UserView(users.get(0));
				session.setAttribute("user", view);				
				result="success";
			}				
			manager.close();
		}
		resp.getWriter().write(result);
	}
}
